#####
# Replication for: "Can Political Speech Foster Tolerance of Immigrants?" by Schleiter, Tavits, and Ward.
# Functions
#####


# Plotting Utilities ------------------------------------------------------

CI_machine <- function(x, level = 0.95){
  x <- na.omit(x)
  main <- mean(x)
  adj <- (1-level)/2
  CI <- main + qt(c(adj, 1-adj), df = length(x) - 1)*sd(x)/sqrt(length(x))
  return(list(main = main,lower = CI[1], upper = CI[2]))
}

# for preparing to plot coefficients with 90 and 95 CIs
extractPlotInfo <- function(model, extractCoefs = 2:4){
  est <- model$coefficients[extractCoefs]
  ci90 <- confint(model, level = .9)[extractCoefs, ]
  ci95 <- confint(model, level = .95)[extractCoefs, ]
  return(cbind(est, ci95, ci90))
}

center <- function(x) (x - mean(x,na.rm = T))/sd(x, na.rm = T)

# Model Fitting -----------------------------------------------------------

flexCov <- function(
  x, # the outcome, unquoted
  covs, # character of covariates to include
  data = pooled, # defaults to the pooled data.
  sample = "Main", # character, as Main, Replication, or Pooled
  treatments = c("CH", "CS", "NM"),
  chatty = T # indicator for printing the regression summary
){
  
  if(!sample %in% c("Main", "Replication", "Pooled")) stop("sample must be one of Main, Replication, or Pooled!")
  
  if(sample == "Main"){
    data <- data[wave != "Replication"]
  }
  
  if(sample == "Replication"){
    data <- data[wave == "Replication"]
    covs <- covs[ !covs == "wave"] # no variation on wave in this sample!
  }
  
  y <- deparse(substitute(x))
  form <- as.formula(paste0( y, " ~ ", paste0(c(treatments, covs), collapse = " + ") ))
  reg <- lm(form, data = data)
  if(chatty) print(summary(reg))
  invisible(reg)
  
}

# wrapper around flexCov that automatically sets to use all covaraites
# removes wave from replication models because there is no variation in the replication
allCov <- function(...){
  flexCov(..., covs = c("female", "age", "ageSq", "race2", "edu2", "pid2", "news2", "region2", "wave"))
}

# wrapper around flexCov that omits covariates entirely
noCov <- function(...){
  flexCov(..., covs = NULL)
}


# Model reporting ---------------------------------------------------------

texregPS <- function(
  ...,
  custom.coef.map = list(
    "NM" =  "Norms",
    "CS" = "Countering Stereotypes",
    "CH" = "Common Humanity"
    ),
  booktabs = T,
  dcolumn = T,
  include.adjrs = F,
  include.rsquared = F,
  include.rmse = F,
  caption.above = T,
  custom.gof.names = "$N$",
  fontsize = "footnotesize",
  stars = c(0.01, 0.05, 0.10),
  digits = 3){
  texreg(
    ...,
    custom.coef.map = custom.coef.map,
    booktabs = booktabs,
    dcolumn = dcolumn,
    include.adjrs = include.adjrs,
    include.rsquared = include.rsquared,
    include.rmse = include.rmse,
    caption.above = caption.above,
    fontsize = fontsize,
    stars = stars,
    digits = digits,
    custom.gof.names = custom.gof.names
  )
}

